package com.wash.shoes.util;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.*;

/**
 * @author lijianguo
 * @Date 2024/7/13 14:46
 * 请输入类的简介
 **/
@Component
public class TableIncCodeUtil {

    private static Log log = LogFactory.getLog(TableIncCodeUtil.class);

    /**
     * 下一个code
     *
     * @return 下一个
     */
    public static String tableNextCode(String tableName, String tableField, String prefix) {
        TableCode tableCode = new TableCode();
        tableCode.setTableName(tableName);
        tableCode.setTableField(tableField);
        tableCode.setPrefix(prefix);
        return tableNextCode(tableCode);
    }

    /**
     * 下一个code
     *
     * @param tableCode 说明
     * @return 下一个
     */
    public static String tableNextCode(TableCode tableCode) {
        // TODO: 2024/9/1 这里应该获取不到 dataSource
        DataSource dataSource = SpringUtil.getBean(DataSource.class);
        PreparedStatement preparedStatement = null;
        try (Connection connection = dataSource.getConnection()) {
            preparedStatement = connection.prepareStatement(tableCode.getSqlStr());
            ResultSet rs = preparedStatement.executeQuery();
            ResultSetMetaData read = rs.getMetaData();
            JSONArray json = new JSONArray();
            while (rs.next()) {
                int numColumns = read.getColumnCount();
                JSONObject obj = new JSONObject();
                for (int i = 1; i <= numColumns; i++) {
                    String column_name = read.getColumnName(i);
                    obj.put(column_name, rs.getObject(column_name));
                }
                json.add(obj);
            }
            if (json.size() == 0) {
                return tableCode.getNextCode(0L, tableCode.getCodeLength());
            } else {
                JSONObject first = (JSONObject) json.get(0);
                return tableCode.getNextCode(first.getLong("maxCode"), tableCode.getCodeLength());
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    log.error(String.valueOf(e));
                }
            }
        }
    }
}
